package org.dromara.websocket.connection;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by       PokerFace
 * Create Date      2023-09-28
 * Email:
 * Version          1.0.0
 * <p>
 * Description:
 */
public class ConnectionManager {

    private ConcurrentHashMap<Channel, Connection> contextConnectionMap;
    private ConcurrentHashMap<Connection, Channel> connectionContextMap;

    private ConnectionListener connectionListener;

    /**
     * Constructor
     *
     */
    public ConnectionManager()
    {

        contextConnectionMap = new ConcurrentHashMap<>();
        connectionContextMap = new ConcurrentHashMap<>();
    }



    public void setConnectionListener(ConnectionListener connectionListener)
    {
        this.connectionListener = connectionListener;
    }


    /**
     *  this method requires when server received connection from client.
     *
     * @param context netty handler context.
     */
    public synchronized void receivedConnection(ChannelHandlerContext context)
    {

        Connection connection = contextConnectionMap.get(context.channel());
        if (connection == null)
        {
            connection = new Connection( context);
            contextConnectionMap.put(context.channel(), connection);
            connectionContextMap.put(connection, context.channel());
        }

        if (connectionListener!= null){
            connectionListener.arrived(connection);
        }
    }


    /**
     *  Connection invalid.
     *
     * @param context context
     */
    public synchronized void removeConnection(ChannelHandlerContext  context)
    {
        Connection  connection = contextConnectionMap.remove(context.channel());
        if (connection != null) {
            connectionContextMap.remove(connection);

            connection.connected = false;
            if (connectionListener!= null){
                connectionListener.disconnected(connection);
            }
        }

    }


    public Connection getConnection(ChannelHandlerContext context)
    {
        Connection  connection = contextConnectionMap.get(context.channel());
        return connection;
    }

}
